package cn.buildoncloud.labor.workermanapplet.util;

import org.apache.commons.codec.binary.Base64;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.*;

/**
 * 文件操作工具类
 * Description: cn.buildoncloud.labor.workermanapplet.util
 * Created by CuiZibo on 2018/11/26 15:55
 */
public class FileUtil {

    /**
     * base64转MultipartFile
     *
     * @return
     */
    public static MultipartFile base64ToMultipart(String base64) {
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b = new byte[0];
            b = decoder.decodeBuffer(base64);

            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            return new BASE64DecodedMultipartFile(b, "data:image/jpeg;base64,");
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * file类型文件转base64字符串
     *
     * @param file
     * @return
     */
    public static String fileToBase64(File file) {
        String base64 = null;
        FileInputStream  in = null;
        try {
            in = new FileInputStream(file);
            byte[] buffer = new byte[(int)file.length()];
            in.read(buffer);
            base64 = Base64.encodeBase64String(buffer);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return base64;
    }

    public static void main(String[] args) {

        File file = new File("C:\\Users\\CuiZibo\\Pictures\\0.jpg");


    }

    public File base64ToJpg(String imgStr) {
        if (imgStr == null) {
            return null;
        }
        File file = null;
        OutputStream out = null;
        try {
            byte[] b = org.apache.commons.codec.binary.Base64.decodeBase64(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            //生成jpeg图片
            out = new FileOutputStream(file);
            out.write(b);
            out.flush();
            return file;
        } catch (Exception e) {
            return null;
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (Exception ex) {

                }

            }
        }
    }


}